package com.omicrondev.flightops;

import android.app.Application;
import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by gdean on 8/2/13.
 */
public class FlightOps extends Application {
    public AcType mAcType = null;

    @Override
    public void onCreate() {
        super.onCreate();

        mAcType = new AcType();

        loadData();
    }

    public void loadData() {
        String json = "{bew:2850,bea:83.5,toLimit:4570,ldgLimit:4342,zfLimit:4000,"
            + "fwdLimits: [{weight:2200,arm:82},{weight:3400,arm:82},{weight:4570,arm:90.6}],"
            + "aftLimits: [{weight:2200,arm:94.6},{weight:4570,arm:94.6}],"
            + "stations: [{name:\"Baggage 1\",arm:22.5,min:0,max:100,fuel:false,hidden:false},"
                + "{name:\"Pilot 1\",arm:85.5,min:0,max:0,fuel:false,hidden:false},"
                + "{name:\"Pilot 2\",arm:85.5,min:0,max:0,fuel:false,hidden:false},"
                + "{name:\"Fuel\",arm:93.6,min:0,max:123,fuel:true,hidden:false},"
                + "{name:\"Passenger 1\",arm:119.1,min:0,max:0,fuel:false,hidden:false},"
                + "{name:\"Passenger 2\",arm:119.1,min:0,max:0,fuel:false,hidden:false},"
                + "{name:\"Passenger 3\",arm:157.6,min:0,max:0,fuel:false,hidden:false},"
                + "{name:\"Passenger 4\",arm:157.6,min:0,max:0,fuel:false,hidden:false},"
                + "{name:\"Baggage 2\",arm:178.7,min:0,max:100,fuel:false,hidden:false}]}";

        try {
            FileInputStream file = openFileInput("data");
            byte buffer[] = new byte[file.available()];
            while (file.read(buffer) != -1);
            file.close();
            json = new String(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }

        mAcType.buildFromJSON(json);

        /*
        // Restore preferences
        SharedPreferences settings = getPreferences(MODE_PRIVATE);
        json = settings.getString("data", json);
        mAcType.buildFromJSON(json);
        */
    }

    public void saveData() {
        String json = mAcType.saveToJSON();

        FileOutputStream fos = null;
        try {
            fos = openFileOutput("data", Context.MODE_PRIVATE);

            fos.write(json.getBytes());

            fos.close();
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    public void removeData() {
        try {
            File dir = getFilesDir();
            File file = new File(dir, "data");
            boolean deleted = file.delete();
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }
}
